use tokio::io::AsyncWriteExt;
use tokio_serial::{Parity, SerialPort, SerialPortBuilderExt, SerialStream};

use crate::{error::{AppErr, ErrWrap}, utils::UnSafeAsMut};


unsafe impl Send for ConnPort {}
unsafe impl Sync for ConnPort {}

pub struct ConnPort {

    stream: SerialStream,
}

impl ConnPort {

    pub fn new(name: &str) -> Result<ConnPort, AppErr> {
      //  let n = tokio_serial::new(name, 115200).open_native().wrap()?;
        
        let stream = tokio_serial::new(name, 115200).open_native_async().wrap()?;
    
        Ok( ConnPort { stream } )
    }

    pub async fn write(&self, buf: &[u8]) -> Result<(), AppErr> {

        if buf.len() <= 0 {
            return Ok(());
        }
        let stream = self.stream.to_mut();

        stream.set_parity(Parity::Mark).wrap()?;
        stream.write_all(&buf[..1]).await?;
        stream.flush().await?;
        stream.set_parity(Parity::Space).wrap()?;
        stream.write_all(&buf[1..]).await?;
        stream.flush().await?;

        Ok(())
    }
}


